package com.westar.base.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA加解密工具类
 */
public class RSAUtils {

    private static String key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgCCPgUvDVc1Wk6gAv8uUGPfcp/BHjwMKtwikE08Y6BVRq1jO7T8GeVG7LhQf1jesiFSncolg7ZEBzbDClIFYOTsXUHfihpPdcYelaveMWsBuWKQmVOpR7KlRuI" +
            "Mmx3FZWrdT5s624/Qh9YDFzFUAwv+YPIwncj6fREb26sTHEJmI8/dLzHZ//BUzWhEHH017oeNjqRW9K/CPxlDM5hY9TADerNZL3y25Q7t2rMoKIMd2lLhAk0+H7mPjPQ4k1Giutx8TOGI+MMXgsBcnVyvzvgvebfJMvqh256qPT" +
            "gyVdX3GwZAjhAkc+uxWHBL7wAFAMV7Wc3V2czZKrziiZ+PGzwIDAQAB";

    static PublicKey publicKey = getPublicKey(key);

    //公钥加密
    public static String encrypt(String content, PublicKey publicKey) {
        try{
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//java默认"RSA"="RSA/ECB/PKCS1Padding"
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(content.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(output);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * String转公钥PublicKey
     * @param key
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key)  {
        byte[] keyBytes;
        try {
            keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            return publicKey;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




}